<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/7/29
 * Time: 14:25
 */

namespace app\controller\index;


use app\common\lib\Common;
use app\common\lib\QRCodeImage;
use app\common\lib\TencentCos;
use app\common\lib\YunZhangHu2;
use app\controller\CoreController;
use app\exception\IndexException;
use app\logic\index\sms\SmsLogic;
use app\logic\index\user\UserLogic;
use support\Cache;
use support\Request;
use support\Response;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

class ToolController extends CoreController
{
    public function getInitConfig(Request $request)
    {
        $data = [];
        $data['ischecking'] = Common::checkIngStatus();

        // 联系客服二维码随机拿
        $customer_service_qrcode_arr = [
            (string)config('param.customer_service_qrcode'),
            (string)config('param.customer_service_qrcode_2')
        ];
        $customer_service_qrcode = $customer_service_qrcode_arr[rand(0,1)];

        // 领取VIP二维码随机拿
        $receive_vip_qrcode_arr = [
            (string)config('param.receive_vip_qrcode'),
            (string)config('param.receive_vip_qrcode_2')
        ];
        $receive_vip_qrcode = $receive_vip_qrcode_arr[rand(0,1)];

        //配置信息
        $data['coupon_time'] = (int)config('param.coupon_time',3600);
        $data['image_consume_point'] = (int)config('param.image_consume_point',10);
        $data['consume_point'] = (int)config('param.consume_point',10);
        $data['original_video_nums'] = (int)config('param.original_video_nums');
        $data['user_income_amount'] = (int)config('param.user_income_amount');
        $data['vip_month_avg_income_amount'] = (string)config('param.vip_month_avg_income_amount');
        $data['customer_service_qrcode'] = $customer_service_qrcode;
        $data['receive_vip_qrcode'] = $receive_vip_qrcode;
        $data['receive_vip_image'] = (string)config('param.receive_vip_image');
        $data['goto_wechat_link'] = (string)config('param.goto_wechat_link');
        $data['home_pop_ups'] = (string)config('param.home_pop_ups','3');
        $data['home_pop_windows'] = (string)config('param.home_pop_windows','3');
        $data['example_open_close'] = (string)config('param.example_open_close','0');
        $data['forbidden_words'] = array_filter(explode('|@@|',config('param.forbidden_words','')));

        foreach([1,2,3] as $k){
            $image = config('param.invit_poster_image_'.$k);
            $image && $data['invit_poster_image'][] = $image;
        }
        $data['invit_qrcode_link'] = config('param.invit_qrcode_link');

        //版本更新
        if(strtoupper($request->platform)=='IOS'){
            $data['update_version'] = config('param.update_version_ios');
        }elseif (strtoupper($request->platform)=='ANDROID'){
            $data['update_version'] = config('param.update_version_android');
        }
        $data['update_version']['is_version_update'] = 0;
        $versions = explode('.',$request->version);
        $updateVersions = explode('.',($data['update_version']['version_number']??''));
        if(isset($updateVersions[2]) && isset($versions[2])){
            $curVersion = $versions[0].'.'.$versions[1].'.'.$versions[2];
            $updateVersion = $updateVersions[0].'.'.$updateVersions[1].'.'.$updateVersions[2];
            if($updateVersion>$curVersion){
                $data['update_version']['is_version_update'] = 1;
            }
        }
        return $this->endSuccess($data);
    }

    public function uploadImage(Request $request)
    {
        $param = [];
        $param['file'] = $request->file('file','');
        $param['path'] = $request->input('path','');
        $param['name'] = $request->input('name','');

        if($request->file('file')==false){
            throw new IndexException(4020,'请上传文件');
        }

        if($request->file('file')->isValid()==false){
            throw new IndexException(4020,'上传失败');
        }

        $param['ext'] = $request->file('file')->getUploadExtension();

        if(in_array(strtolower($param['ext']),['jpg','jpeg','gif','png','mp4'])==false){
            throw new IndexException(4020,'请上传图片或视频');
        }

        $path = 'image';
        $path .= !empty($param['path']) ? '/'.trim($param['path'],'/') : '';
        if(config('app.app_env')=='local'){
            $filePath = $path.'/'.date('ymd').'/'.substr(md5($request->file('file')->getUploadName().uniqid()),'-20').'.'.$param['ext'];
            Common::mkdirs(dirname(public_path($filePath)));
            copy($request->file('file')->getRealPath(),public_path($filePath));
            @unlink($request->file('file')->getRealPath());

            $result = [
                'src'=>config('app.app_url').'/'.$filePath,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }else{

            $name = $param['name'] ? $param['name'].'.'.$param['ext'] : '';
            $res = TencentCos::getInstance()->uploadFormFile($request->file('file'),$path,$name);
            $videoLink = 'https://'.$res['Location'];

            $result = [
                'src'=>$videoLink,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }

        return $this->endSuccess($result);
    }
    public function uploadVoice(Request $request)
    {
        $param = [];
        $param['file'] = $request->file('file','');
        $param['path'] = $request->input('path','');
        $param['name'] = $request->input('name','');

        if($request->file('file')==false){
            throw new IndexException(4020,'请上传文件');
        }

        if($request->file('file')->isValid()==false){
            throw new IndexException(4020,'上传失败');
        }

        $param['ext'] = $request->file('file')->getUploadExtension();

        if(in_array(strtolower($param['ext']),['mp3','wav','m4a'])==false){
            throw new IndexException(4020,'请上传音频');
        }

        $path = 'audio';
        $path .= !empty($param['path']) ? '/'.trim($param['path'],'/') : '';

        if(config('app.app_env')=='local'){
            $filePath = $path.'/'.date('ymd').'/'.substr(md5($request->file('file')->getUploadName().uniqid()),'-20').'.'.$param['ext'];
            Common::mkdirs(dirname(public_path($filePath)));
            copy($request->file('file')->getRealPath(),public_path($filePath));
            @unlink($request->file('file')->getRealPath());

            $result = [
                'src'=>config('app.app_url').'/'.$filePath,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }else{

            $name = $param['name'] ? $param['name'].'.'.$param['ext'] : '';
            $res = TencentCos::getInstance()->uploadFormFile($request->file('file'),$path,$name);
            $videoLink = 'https://'.$res['Location'];

            $result = [
                'src'=>$videoLink,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }

        return $this->endSuccess($result);
    }

    public function uploadVideo(Request $request)
    {
        $param = [];
        $param['file'] = $request->file('file','');
        $param['path'] = $request->input('path','');
        $param['name'] = $request->input('name','');

        if($request->file('file')==false){
            throw new IndexException(4020,'请上传文件');
        }

        if($request->file('file')->isValid()==false){
            throw new IndexException(4020,'上传失败');
        }

        $param['ext'] = $request->file('file')->getUploadExtension();

        if(in_array(strtolower($param['ext']),['mp4','avi','mov','wav'])==false){
            throw new IndexException(4020,'请上传视频');
        }

        $path = 'video';
        $path .= !empty($param['path']) ? '/'.trim($param['path'],'/') : '';
        if(config('app.app_env')=='local'){
            $filePath = $path.'/'.date('ymd').'/'.substr(md5($request->file('file')->getUploadName().uniqid()),'-20').'.'.$param['ext'];
            Common::mkdirs(dirname(public_path($filePath)));
            file_put_contents(public_path($filePath),file_get_contents($request->file('file')->getRealPath()));

            $result = [
                'src'=>config('app.app_url').'/'.$filePath,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }else{
            $name = $param['name'] ? $param['name'].'.'.$param['ext'] : '';
            $res = TencentCos::getInstance()->uploadFormFile($request->file('file'),$path,$name);
            $videoLink = 'https://'.$res['Location'];

            $result = [
                'src'=>$videoLink,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }

        return $this->endSuccess($result);
    }

    public function asyncUploadVideo(Request $request)
    {
        $param = [];
        $param['file'] = $request->file('file','');
        $param['ext'] = $request->input('ext','mp4');
        $param['name'] = $request->input('name','');

        if($request->file('file')->isValid()==false){
            throw new IndexException(4020,'上传失败');
        }

        if(in_array(strtolower($param['ext']),['mp4','avi','mov','wav'])==false){
            throw new IndexException(4020,'请上传视频');
        }

        $path = 'video';
        $path .= !empty($param['path']) ? '/'.trim($param['path'],'/') : '';
        if(config('app.app_env')=='local'){
            $filePath = $path.'/'.date('ymd').'/'.substr(md5($request->file('file')->getUploadName()),'-12').'.'.$param['ext'];
            Common::mkdirs(dirname(public_path($filePath)));
            file_put_contents(public_path($filePath),file_get_contents($request->file('file')->getRealPath()));

            $result = [
                'src'=>config('app.app_url').'/'.$filePath,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }else{
            $name = $param['name'] ? $param['name'].'.'.$param['ext'] : '';
            $res = TencentCos::getInstance()->uploadLocalFile($request->file('file'),$path,$name);
            $videoLink = 'https://'.$res['Location'];

            $result = [
                'src'=>$videoLink,
                'res'=>'true',
                'filename'=>$request->file('file')->getUploadName(),
            ];
        }

        return $this->endSuccess($result);
    }

    public function generateQrcode(Request $request)
    {
        return QRCodeImage::getInstance()->generateQrCode('http://baidu.com');
    }

    public function sendSmsAuthCode(Request $request)
    {
        $param= [];
        $param['mobile'] = $request->input('mobile');
        $param['auth_type'] = $request->input('auth_type');
        if(empty($param['mobile'])){
            throw new IndexException(4020,'手机号必传');
        }
        if(empty($param['auth_type'])){
            throw new IndexException(4020,'验证类型必传');
        }
        $data = SmsLogic::getInstance()->sendSmsAuthCode($param);
        return $this->endSuccess($data);
    }

    /**
     * 验证码
     * @param Request $request
     * @param string $type
     * @return Response
     */
    public function getCaptcha(Request $request): Response
    {
        $builder = new PhraseBuilder(4, '0123456789');
        $captcha = new CaptchaBuilder(null, $builder);
        $captcha->setBackgroundColor(225,250,239);
        $captcha->setTextColor(9,190,109);
        $captcha->setTextSize(40);
        $captcha->setIgnoreAllEffects(true);
        $captcha->setMaxAngle(0);
        $captcha->setMaxOffset(0);
        $captcha->build(144,88);

        $requestId = md5(round(microtime(true) * 10000) . (request()->getRealIp()) . (mt_rand(1000, 9999)));
        Cache::set("captcha-".$requestId, strtolower($captcha->getPhrase()), 60);
        $img_content = $captcha->get();

        return $this->endSuccess(['url'=>'data:image/png;base64,'.base64_encode($img_content),'key'=>$requestId]);
        //return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function checkCaptcha(Request $request): Response
    {
        $code = $request->input('authcode');
        $key = $request->input('key');
        $authCode = Cache::get("captcha-".$key);
        $status = 0;
        if(strtolower($code)==strtolower($authCode)){
            $status = 1;
        }
        return $this->endSuccess(['status'=>$status]);
    }

    public function getYunZhangHuContract(Request $request): Response
    {
        $data = YunZhangHu2::getInstance()->getUserContract();
        return $this->endSuccess($data);
    }

    public function receiveVipByMobile(Request $request): Response
    {
        $param = [];
        $param['mobile'] = $request->input('mobile');
        if(empty($param['mobile'])){
            throw new IndexException(4020,'手机号不能为空');
        }
        $result = UserLogic::getInstance()->receiveVipByMobile($param);

        return $this->endSuccess($result);
    }

    public function getForbiddenWordsList(Request $request): Response
    {
        $data = [];
        $data['forbidden_words'] = array_filter(explode('|@@|',config('param.forbidden_words','')));
        $data['forbidden_words'] = $data['forbidden_words'] ? $data['forbidden_words'] : [];

        return $this->endSuccess($data);
    }
}
